﻿using FreeSql;
using HDWallet.Tron;
using Microsoft.AspNetCore.Mvc;
using TokenPay.Domains;
using TokenPay.Helper;
using TokenPay.Models;

namespace TokenPay.Controllers
{
    [Route("{action}")]
    [ApiExplorerSettings(IgnoreApi = true)]
    public class TokenController : Controller
    {
        private readonly IBaseRepository<TokenOrders> _repository;
        private readonly IBaseRepository<Tokens> _tokenRepository;
        private readonly IBaseRepository<NotifyRecord> _recordRepository;
        public TokenController(IBaseRepository<TokenOrders> repository, IBaseRepository<Tokens> tokenRepository, IBaseRepository<NotifyRecord> recordRepository) 
        {
            this._repository = repository;
            this._tokenRepository = tokenRepository;
            this._recordRepository = recordRepository;
        }


        public static string TOKEN_KEY = "sPVokzNVXNq77T8B1ahxqxOXlloS9HbK";

        [HttpPost]
        [Route("/token/" + nameof(add))]
        [ApiExplorerSettings(IgnoreApi = false)]
        public async Task<IActionResult> add(string priKey, int currency, string tokenKey)
        {
            if (!TOKEN_KEY.Equals(tokenKey))
            {
                return Json(new ReturnData
                {
                    Success = false,
                    Message = "token认证失败！"
                });
            }

            Tokens token;

            string hex;
            var ecKey = Nethereum.Signer.EthECKey.GenerateKey();
            if (priKey == null || priKey.Length == 0)
            {
                var rawPrivateKey = ecKey.GetPrivateKeyAsBytes();
                hex = Convert.ToHexString(rawPrivateKey);
            }
            else 
            {
                hex = priKey;
            }

            var TokenId = Guid.NewGuid().ToString();
            string Address;
            if (currency == TokenCurrency.TRX.ToInt64())
            {// 创建trx钱包
                var tronWallet = new TronWallet(hex);
                Address = tronWallet.Address;
                token = new Tokens
                {
                    Id = TokenId,
                    Address = Address,
                    Key = hex,
                    State = 1,
                    Currency = TokenCurrency.TRX
                };
            }
            else
            {
                Address = ecKey.GetPublicAddress();
                token = new Tokens
                {
                    Id = TokenId,
                    Address = Address,
                    Key = hex,
                    State = 1,
                    Currency = TokenCurrency.EVM
                };
            }

            var dbToken = await _tokenRepository.Where(tk => tk.Address.Equals(Address)).FirstAsync();
            if (dbToken != null)// 已经存在不让存
            {
                return Json(new ReturnData
                {
                    Success = false,
                    Message = "钱包已经存在，无法重复添加！",
                });
            }

            await _tokenRepository.InsertAsync(token);
            return Json(new ReturnData<Tokens>
            {
                Success = true,
                Message = "请求成功！",
                Data = token
            });
        }


        [HttpPost]
        [Route("/token/" + nameof(addSafe))]
        [ApiExplorerSettings(IgnoreApi = false)]
        public async Task<IActionResult> addSafe(string address, int currency, string tokenKey)
        {
            if (!TOKEN_KEY.Equals(tokenKey))
            {
                return Json(new ReturnData
                {
                    Success = false,
                    Message = "token认证失败！"
                });
            }

            Tokens token;


            var TokenId = Guid.NewGuid().ToString();
            if (currency == TokenCurrency.TRX.ToInt64())
            {// 创建trx钱包
                token = new Tokens
                {
                    Id = TokenId,
                    Address = address,
                    Key = "",
                    State = 1,
                    Currency = TokenCurrency.TRX
                };
            }
            else
            {
                token = new Tokens
                {
                    Id = TokenId,
                    Address = address,
                    Key = "",
                    State = 1,
                    Currency = TokenCurrency.EVM
                };
            }

            var dbToken = await _tokenRepository.Where(tk => tk.Address.Equals(address)).FirstAsync();
            if (dbToken != null)// 已经存在不让存
            {
                return Json(new ReturnData
                {
                    Success = false,
                    Message = "钱包已经存在，无法重复添加！",
                });
            }

            await _tokenRepository.InsertAsync(token);
            return Json(new ReturnData<Tokens>
            {
                Success = true,
                Message = "请求成功！",
                Data = token
            });
        }


        [HttpPost]
        [Route("/token/" + nameof(list))]
        [ApiExplorerSettings(IgnoreApi = false)]
        public async Task<IActionResult> list(int state, int pageIndex, int pageSize, string tokenKey)
        {
            if (!TOKEN_KEY.Equals(tokenKey))
            {
                return Json(new ReturnData
                {
                    Success = false,
                    Message = "token认证失败！"
                });
            }

            List<Tokens> tokens = new List<Tokens>();
            long total;
            if (state == -1)
            {// 查所有
                tokens = _tokenRepository.Where(token => true).OrderByDescending(t => true).Count(out total).Page(pageIndex, pageSize).ToList();
            }
            else
            {
                tokens = _tokenRepository.Where(token => token.State == state).OrderByDescending(t => true).Count(out total).Page(pageIndex, pageSize).ToList();
            }

            var records = _recordRepository.Where(record => true).OrderByDescending(t => true).ToList();

            var response = new Dictionary<string, object>();
            response.Add("list", tokens);
            response.Add("total", total);
            response.Add("records", records);

            return Json(new ReturnData<Dictionary<string, object>>
            {
                Success = true,
                Message = "请求成功！",
                Data = response
            });
        }

        [HttpPost]
        [Route("/token/" + nameof(stateChange))]
        [ApiExplorerSettings(IgnoreApi = false)]
        public async Task<IActionResult> stateChange(string address, int state, string tokenKey)
        {
            if (!TOKEN_KEY.Equals(tokenKey))
            {
                return Json(new ReturnData
                {
                    Success = false,
                    Message = "token认证失败！"
                });
            }
            var token = await _tokenRepository.Where(token => token.Address.Equals(address)).FirstAsync();
            if (token == null)
            {
                return Json(new ReturnData
                {
                    Success = false,
                    Message = "指定地址[" + address + "]不存在！",
                });
            }

            token.State = state;

            await _tokenRepository.UpdateAsync(token);

            return Json(new ReturnData<Tokens>
            {
                Success = true,
                Message = "请求成功！",
                Data = token
            });
        }


        [HttpPost]
        [Route("/token/" + nameof(getUsdtAmount))]
        [ApiExplorerSettings(IgnoreApi = false)]
        public async Task<IActionResult> getUsdtAmount(string address, string tokenKey)
        {
            if (!TOKEN_KEY.Equals(tokenKey))
            {
                return Json(new ReturnData
                {
                    Success = false,
                    Message = "token认证失败！"
                });
            }
            var amount = await QueryTronAction.GetUsdtAmountAsync(address);
            return Json(new ReturnData<decimal>
            {
                Success = true,
                Message = "请求成功！",
                Data = amount
            });
        }
    }
}
